package com.android.taobao;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.taobao.api.TaobaoGetUser;
import com.android.taobao.api.TaobaoItemCatsGet;
import com.android.taobao.cache.CachePool;
import com.android.taobao.common.Common;
import com.android.taobao.database.DataBase;
import com.android.taobao.sessionkey.GetSessionKey;
import com.taobao.api.model.ItemCat;
import com.taobao.api.model.User;

public class Test extends Activity {
	private EditText et, catEt;
	private Button confimrButton, authCodeButton, showCatButton;
	private ProgressDialog pd;
	private User user;
	private Handler handler = new Handler();
	private BufferedReader br;
	private InputStreamReader isr;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test);
		confimrButton = (Button) findViewById(R.id.Button01);
		authCodeButton = (Button) findViewById(R.id.Button02);
		et = (EditText) findViewById(R.id.EditText01);
		catEt = (EditText) findViewById(R.id.EditText02);
		showCatButton = (Button) findViewById(R.id.Button03);
		// 初始化更新类目
		getItemCatsIntoDataBase();
		confimrButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				getSessionKey(et.getText().toString().trim());
			}
		});
		authCodeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				getAuthCode();
			}
		});
		showCatButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showItemCat(catEt.getText().toString().trim());
			}
		});
	}

	/**
	 * getAuthCode from the TAOBAO websites by Browser
	 */
	private void getAuthCode() {

		pd = ProgressDialog.show(Test.this, "title",
				"going to the website now...", true);
		new Thread() {
			public void run() {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri
						.parse(Common.TEST_HOST + Common.TEST_PAGE
								+ Common.TEST_AUTH_PARAM + Common.APP_KEY));
				pd.dismiss();
				startActivity(intent);
			}
		}.start();
	}

	/**
	 * getItemCatsIntoFile
	 */
	public void getItemCatsIntoFile() {
		new Thread() {
			public void run() {
				try {
					Context ctx = Test.this;
					OutputStreamWriter osw = new OutputStreamWriter(ctx
							.openFileOutput("test.txt", Context.MODE_PRIVATE));
					List<ItemCat> cats = TaobaoItemCatsGet.getItemCats();
					for (ItemCat cat : cats) {
						osw.write(cat.getCid() + "#" + cat.getName() + "#"
								+ cat.getStatus() + "#" + cat.getSortOrder()
								+ "#" + cat.getParentCid() + "#"
								+ cat.getIsParent() + "\n");
					}
					osw.close();
					isr = new InputStreamReader(ctx.openFileInput("test.txt"));
					br = new BufferedReader(isr);
					handler.post(new Runnable() {
						public void run() {
							try {
								new AlertDialog.Builder(Test.this).setMessage(
										br.readLine()).setPositiveButton(
										"Okay", null).show();
							} catch (Exception e) {

							}
						}
					});
					br.close();
					isr.close();
				} catch (Exception e) {
					Log.i("TaobaoItemCatsGet", "Exception", e);
				}
			}

		}.start();
	}

	/**
	 * 新建或更新类目到数据库
	 */

	private void getItemCatsIntoDataBase() {
		new Thread() {
			public void run() {
				try {
					List<ItemCat> cats = TaobaoItemCatsGet.getItemCats();
					for (ItemCat cat : cats) {
						DataBase.getInstance(Test.this).saveOrUpdateItemCats(
								cat);
					}
					handler.post(new Runnable() {
						public void run() {
							new AlertDialog.Builder(Test.this).setMessage(
									"客户端更新类目属性完成！").setPositiveButton("Okay",
									null).show();
						}
					});

				} catch (Exception e) {
					Log.i("TaobaoItemCatsGet", "Exception", e);
				}
			}

		}.start();
	}

	/**
	 * 根据CID显示类目
	 * 
	 * @param cid
	 */

	private void showItemCat(String cid) {

		StringBuilder result = new StringBuilder("");
		ItemCat cat = DataBase.getInstance(Test.this).getItemCat(cid);
		if (null != cat) {
			result.append(cat.getCid() + "\n").append(cat.getName() + "\n")
					.append(cat.getStatus() + "\n").append(
							cat.getSortOrder() + "\n").append(
							cat.getParentCid() + "\n").append(
							cat.getIsParent() + "\n");
		}
		final String showResult = result.toString();
		handler.post(new Runnable() {
			public void run() {
				new AlertDialog.Builder(Test.this).setMessage(
						"".equals(showResult) ? "不存在该CID对应的属性！" : showResult)
						.setPositiveButton("Okay", null).show();
			}
		});
	}

	/**
	 * get SessionKey from the authCode that user input
	 */
	private void getSessionKey(final String authCode) {
		pd = ProgressDialog.show(Test.this, "与淘宝平台确认中...", "请稍后...", true);
		new Thread() {
			public void run() {
				Log.i("sessionKey", GetSessionKey.getSessionKey(authCode));
				pd.dismiss();
				showUserDetail((String) CachePool.get(Common.VISITOR_NICK));
			}
		}.start();
	}

	public void showUserDetail(String nick) {
		try {
			user = TaobaoGetUser.getUser(nick);
			handler.post(new Runnable() {
				public void run() {
					new AlertDialog.Builder(Test.this)
							.setMessage(
									user.getNick() + ":"
											+ user.getLocation().getCity())
							.setPositiveButton("Okay",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											Intent i = new Intent(Test.this,
													Main.class);
											startActivity(i);
										}
									}).show();
				}
			});

		} catch (Exception e) {
			Log.i("TaobaoGetUser", "Exception", e);
		}
	}
}